/**
 * Tiem:   2023-02-18
 * File:   打车任务订单列表
 * Editor: Hd
*/

import React, { Component } from 'react';
import TheQueryForm from '@/components/TheQueryForm';
import TheTableExtend from '@/components/TheTableExtend';
import store from "@/store/store";
import TheButton from "@/components/TheButton";
import ThePagination from "@/components/ThePagination";
import { Table, Radio, Tooltip } from "antd";
import { apiGetTaxiOrder, } from "@/request/petTaxi";
import { getDateTime3 } from '@/utils/getDate';
import { exportSheetTable } from '@/utils/exportTable';
import moment from 'moment';
import _ from 'lodash';
import "./style/index.less";

class TaxiOrder extends Component {
    constructor(props) {
        super();
        this.queryFormRef = React.createRef()
        this.heightRef = React.createRef()
        this.searchRef = React.createRef()
        this.pageHeight = React.createRef()
        this.refs = React.createRef()
        this.tableRefs = React.createRef()
        this.state = {
            form_show: true,
            down_loading: false,
            columns: [
                {
                    title: "创建时间",
                    dataIndex: "createTime",
                    key: "createTime",
                    width: 150,
                    render: (text) => {
                        return <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip>
                    }
                },
                {
                    title: "订单ID",
                    dataIndex: "orderId",
                    key: "orderId",
                },
                {
                    title: "订单编号",
                    dataIndex: "orderCode",
                    key: "orderCode",
                },
                {
                    title: "订单内容",
                    dataIndex: "content",
                    key: "content",
                    ellipsis: {
                        showTitle: false,
                    },
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 180,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return text ? <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip> : "-"
                    }
                },
                {
                    title: "下单用户",
                    dataIndex: "createUserInfo",
                    key: "createUserInfo",
                    render: (text, render) => {
                        return text ?? "-"
                    }
                },
                {
                    title: "打车联系人",
                    dataIndex: "customerInfo",
                    key: "customerInfo",
                    ellipsis: {
                        showTitle: false,
                    },
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 180,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return text ? <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip> : "-"
                    }
                },
                {
                    title: "实收金额（元）",
                    dataIndex: "receiptPrice",
                    key: "receiptPrice",
                    render: (text, render) => {
                        return (text / 100).toFixed(2) ?? "-"
                    }
                },
                // {
                //     title: "优惠金额",
                //     dataIndex: "discountPrice",
                //     key: "discountPrice",
                //     render: (text, render) => {
                //         return (text / 100).toFixed(2) ?? "-"
                //     }
                // },
                {
                    title: "任务",
                    dataIndex: "taskId",
                    key: "taskId",
                    render: (text, render) => {
                        return text ? <TheButton onClick={() => this.props.history.push(`/missions/detail/${text}`)}>{text}</TheButton> : "-"
                    }
                },
                {
                    title: "订单状态",
                    dataIndex: "orderStatus",
                    key: "orderStatus",
                    render: (text) => {
                        let taskStatus = ''
                        switch (text) {
                            case 1:
                                taskStatus = '待支付'
                                break;
                            case 2:
                                taskStatus = '已支付'
                                break;
                            case 3:
                                taskStatus = '已关闭'
                                break;
                            default:
                                break;
                        }
                        return taskStatus
                    }
                },
                {
                    title: "退款/售后",
                    dataIndex: "refundStatus",
                    key: "refundStatus",
                    render: (text) => {
                        let refundStatus = ''
                        switch (text) {
                            case 1:
                                refundStatus = "退款中" 
                                break;
                            case 2:
                                refundStatus = "退款成功" 
                                break;
                            case 3:
                                refundStatus = "退款关闭" 
                                break;
                            case 4:
                                refundStatus = "退款异常" 
                                break;
                            default:
                                refundStatus = "-" 
                                break;
                        }
                        return refundStatus 
                    }
                },
                {
                    title: "备注",
                    dataIndex: "remark",
                    key: "index",
                    onCell: () => {
                        return {
                            style: {
                                maxWidth: 180,
                                overflow: 'hidden',
                                whiteSpace: 'nowrap',
                                textOverflow: 'ellipsis',
                                cursor: 'pointer'
                            }
                        }
                    },
                    render: (text) => {
                        return <Tooltip placement="topLeft" title={text}>
                            {text}
                        </Tooltip>
                    }
                },
                {
                    title: "操作",
                    fixed: 'right',
                    render: (text, render) => {
                        return <div>
                            <TheButton onClick={() => this.view(render)}>查看详情</TheButton>
                        </div>
                    }
                },
            ],
            pageData: {
                pageNo: 1,
                pageSize: 10
            },
            total: "",
            newColumns: [],
            dataSource: [],
            queryForm: {},
            orderStatus: "",
            searchOption: [
                { field: 'orderCode', label: '订单编号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'code', label: '任务单号', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                // { field: 'status', label: '任务类型', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '宠物打车', value: '0', }, { label: '酒店打车', value: '1' }], defaultValue: '' },
                { field: 'content', label: '订单内容', placeholder: '请输入', required: false, rules: [], type: 'Input', defaultValue: '' },
                { field: 'time', label: '下单时间', placeholder: '', required: false, rules: [], type: 'RangePicker', defaultValue: '' },
                // { field: 'driverId', label: '所属司机', placeholder: '请选择', required: false, rules: [], type: 'Select', txt: 'nickname', value: 'driverId', options: [], defaultValue: '' },
                // { field: 'status', label: '任务状态', placeholder: '请选择', required: false, rules: [], type: 'Select', options: [{ label: '未完成', value: '0', }, { label: '已完成', value: '1' }], defaultValue: '' },
            ],
            tableHeight: '',
            Height: '',
        }
    }
    //Initialization
    componentDidMount() {
        this.onColumnsFilter(this.state.columns)
        let searchParams = store.getState().searchValue
        let cacheData = store.getState().dataSource
        let { pageNo, pageSize, queryForm, orderStatus ,pathName} = searchParams
        let Height = this.pageHeight.current.clientHeight - this.searchRef.current.offsetHeight - 50
        let tableHeight = Height - 150
        if (queryForm && queryForm.startCreateTime) {
            queryForm.time = [moment(queryForm.startCreateTime, 'YYYY/MM/DD'), moment(queryForm.endCreateTime, 'YYYY/MM/DD')]
        }
        this.setState({
            tableHeight,
            Height
        })
        if (cacheData) {
            this.setState({
                dataSource: cacheData.dataSource,
                queryForm,
                orderStatus,
                pageData: {
                    pageNo, pageSize
                },
                total: cacheData.total
            }, () => {
                this.queryFormRef.onSetDefault({
                    ...queryForm
                })
                store.dispatch({
                    type: 'ClearDataSource',
                    data: ""
                })
            })
        } else {
            if (searchParams && pageNo&&pathName == 'petTaxiOrder') {
                this.setState({
                    queryForm,
                    orderStatus,
                    pageData: {
                        pageNo, pageSize
                    }
                }, () => {
                    this.queryFormRef.onSetDefault({
                        ...queryForm
                    })
                    this.getData()
                })
            } else {
                this.getData()
            }
        }
        this.tableScrollView()
    }
    //CTRL
    //表格title
    onColumnsFilter(value) {
        this.setState({
            newColumns: value
        })
    }
    //获取数据
    getData = async (values) => {
        const { orderStatus } = this.state
        let { pageNo, pageSize } = this.state.pageData
        if (values && !_.isEmpty(values.time)) {
            values.startCreateTime = getDateTime3(values.time[0]) + ' 00:00:00'
            values.endCreateTime = getDateTime3(values.time[1]) + ' 23:59:59'
            delete (values.time)
        }
        this.setState({
            queryForm: values === undefined ? this.state.queryForm : { ...values, }
        }, async () => {
            const params = {
                pageNo, pageSize, orderStatus, queryForm: this.state.queryForm
            }
            store.dispatch({
                type: 'SaveSearchValues',
                data: {
                    pathName:'petTaxiOrder',
                    ...params
                }
            })
            let res = await apiGetTaxiOrder({
                pageNo, pageSize, orderStatus, ...this.state.queryForm
            })
            if (res.code === 0 && res.data) {
                this.setState({ dataSource: res.data, pageData: { pageNo: res.pageNo, pageSize: res.pageSize }, total: res.totalCount })
            }
        })
    }

    //导出
    export = async () => {
        let params = this.state.queryForm
        this.setState({ down_loading: true })
        await apiGetTaxiOrder({ pageNo: 1, pageSize: -1, ...params })
            .then(res => {
                if (res.code === 0) {
                    let tH_data = [
                        {
                            title: '宠物打车订单列表',
                            prop: '',
                            children: [
                                { prop: 'createTime', title: '创建时间' },
                                { prop: 'orderId', title: '订单ID' },
                                { prop: 'orderCode', title: '订单编号' },
                                { prop: 'content', title: '订单内容' },
                                { prop: 'createUserInfo', title: '下单用户' },
                                { prop: 'customerInfo', title: '打车联系人' },
                                { prop: 'receiptPrice', title: '实收金额（元）', valueType: 'number' },
                                { prop: 'refundPrice', title: '退款金额（元）', valueType: 'number' },
                                // { prop: 'discountPrice', title: '优惠金额', valueType: 'number' },
                                { prop: 'taskId', title: '任务' },
                                { prop: 'orderStatus', title: '订单状态' },
                                { prop: 'refundStatus', title: '退款/售后' },
                                { prop: 'remark', title: '备注' },
                            ]
                        }
                    ]
                    let tB_data = res.data.map(item => {
                        let orderStatus = ''
                        switch (item.orderStatus) {
                            case 1:
                                orderStatus = '待支付'
                                break;
                            case 2:
                                orderStatus = '已支付'
                                break;
                            case 3:
                                orderStatus = '已关闭'
                                break;
                            default:
                                orderStatus = '/'
                                break;
                        }
                        let refundStatus = ''
                        switch (item.refundStatus) {
                            case 1:
                                refundStatus = "退款中" 
                                break;
                            case 2:
                                refundStatus = "退款成功" 
                                break;
                            case 3:
                                refundStatus = "退款关闭" 
                                break;
                            case 4:
                                refundStatus = "退款异常" 
                                break;
                            default:
                                refundStatus = "/" 
                                break;
                        }
                        return {
                            createTime: item.createTime ?? "/",
                            orderId: item.orderId ?? "/",
                            orderCode: item.orderCode ?? "/",
                            content: item.content ?? "/",
                            createUserInfo: item.createUserInfo ?? "/",
                            customerInfo: item.customerInfo ?? "/",
                            receiptPrice: (item.receiptPrice / 100).toFixed(2) ?? "/",
                            refundPrice: (item.refundPrice / 100).toFixed(2) ?? "/",
                            // discountPrice: (item.discountPrice / 100).toFixed(2) ?? "/",
                            taskId: item.taskId ?? "/",
                            orderStatus: orderStatus,
                            refundStatus: refundStatus ,
                            remark: item.remark ?? "/",
                        }
                    })
                    this.setState({ down_loading: false })
                    exportSheetTable({
                        fileName: '打车订单列表', tH_data: tH_data, tB_data: tB_data, isSheet: true, merge: false,
                    })
                }
            })
            .catch(err => {
                React.$message({
                    type: 'warning',
                    content: '导出操作失败,请重试'
                })
                this.setState({ down_loading: false })
            })
    }

    //分页查询
    pageChange = (pageNo, pageSize) => {
        this.setState({
            pageData: {
                pageNo, pageSize
            }
        }, () => {
            this.getData()
        })
    }

    //重置
    onReset() {
        this.setState({
            orderStatus: "",
            queryForm: {}
        }, () => {
            this.pageChange(1, 10)
        })
    }

    //搜索
    onFormSearch(values) {
        this.setState({
            pageData: { pageNo: 1, pageSize: 10 }
        }, () => {
            this.getData(values)
        })
    }

    //状态按钮切换
    handleStatusChange = (e) => {
        let { queryForm, orderStatus } = this.state
        orderStatus = e.target.value
        this.setState({
            orderStatus,
        }, () => {
            this.queryFormRef.onSetDefault({
                ...queryForm
            })
            this.getData()
        })
    }

    //查看详情
    view = (render) => {
        this.tableScrollView()
        const { dataSource, total } = this.state
        store.dispatch({
            type: 'SaveDataSource',
            data: {
                dataSource,
                total
            }
        })
        this.props.history.push(`/order/detail/${render.orderId}`);
    }

    tableScrollView() {
        const tableScrollTop = store.getState().tableScrollTop
        const v = document.getElementsByClassName("ant-table-body")[0]
        if (tableScrollTop) {
            setTimeout(() => {
                v.scrollTop = tableScrollTop
            }, 500)
            store.dispatch({
                type: 'Clear_tableScrollTop',
                data: 0
            })
        } else {
            store.dispatch({
                type: 'Set_tableScrollTop',
                data: v.scrollTop
            })
        }
    }
    //View
    render() {
        let { columns, form_show, searchOption, newColumns, dataSource, pageData, total, orderStatus } = this.state
        return (
            <div className='missionsPage' ref={this.pageHeight}>
                <div ref={this.searchRef}>
                    <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
                        onReset={() => this.onReset()}
                        onGetValues={(values) => { this.onFormSearch(values) }} >
                    </TheQueryForm>
                    <TheTableExtend
                        columns={columns}
                        onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
                        onTableRefresh={() => this.getData()}
                        onColumnsFilter={(value) => this.onColumnsFilter(value)}
                    >
                        <TheButton size="middle" onClick={() => this.export()} type="primary">导出</TheButton>
                        <Radio.Group defaultValue={orderStatus} onChange={this.handleStatusChange}>
                            <Radio.Button value="">全部</Radio.Button>
                            <Radio.Button value="1">待支付</Radio.Button>
                            <Radio.Button value="2">已支付</Radio.Button>
                            <Radio.Button value="3">已关闭</Radio.Button>
                        </Radio.Group>
                    </TheTableExtend>
                </div>
                <div className='p-layout-content-pagination'>
                    <Table columns={newColumns} dataSource={dataSource} pagination={false} bordered={1}
                        scroll={{ x: 'max-content', y: '55vh' }} ref={this.tableRefs} id='tabel'
                    ></Table>
                    <ThePagination
                        pageNo={pageData.pageNo}
                        pageSize={pageData.pageSize}
                        total={total}
                        pageChange={this.pageChange}
                    />
                </div>

            </div>
        )
    }
}

export default TaxiOrder
